<script setup>
import {shallowReactive, shallowRef} from "vue";
import {RULE} from "@/const";
import {ElMessage} from "element-plus";
import router from "@/router";
import MyNav from "@/components/MyNav.vue";
import MyForm from "@/components/MyForm.vue";
import {updatePasswordApi} from "@/api/EmpApi";

// 表单项
let items = shallowRef([
  {'label': '原密码', 'prop': 'oldPassword', 'type': 'password', 'required': true, 'placeholder': '请输入原密码'},
  {'label': '新密码', 'prop': 'newPassword', 'type': 'password', 'required': true, 'placeholder': '请输入新密码'},
  {'label': '确认密码', 'prop': 'rePassword', 'type': 'password', 'required': true, 'placeholder': '请确认新密码'},
]);

// 表单值
let data = shallowReactive({});

// 表单规则
let rules = {
  'oldPassword': RULE.PASSWORD,
  'newPassword': [
    {pattern: /^[_a-zA-Z0-9]{4,20}$/, message: '密码须由4到20个字母，数字或下划线组成'},
    {
      validator: (rule, value, callback) => {
        if (value === data['oldPassword']) {
          callback('新旧密码不能相同');
        } else {
          callback();
        }
      }
    }
  ],
  'rePassword': [
    {pattern: /^[_a-zA-Z0-9]{4,20}$/, message: '密码须由4到20个字母，数字或下划线组成'},
    {
      validator: (rule, value, callback) => {
        if (value !== data['newPassword']) {
          callback('两次密码不一致');
        } else {
          callback();
        }
      }
    }
  ],
};

/* ==================== 修改成功后 ==================== */
function updateSuccess(){
  ElMessage("修改个人密码后需要重新登录！");
  setTimeout(() => router.push('/'), 500);
}

</script>

<template>

  <my-nav :items="[
    {'icon': 'User', 'label': 'DashBoard', 'url': '/DashBoard'},
    {'icon': 'User', 'label': '修改个人密码'},
  ]"/>

  <el-divider/>

  <el-card class="updatePassword-body" header="修改个人密码">
    <my-form type="update" :items="items" :data="data" :rules="rules"
             :api="updatePasswordApi" :fn="updateSuccess"/>
  </el-card>

</template>

<style scoped lang="scss">
.updatePassword-body {
  margin: 70px auto 0;
  width: 30%;
}
</style>

